import Vue from 'vue'
import Router from 'vue-router'
import { getToken } from '@/utils/auth'

import Login from '@/views/Login'
import Layout from '@/views/Layout'
import Home from '@/views/Home'
import UserList from '@/views/User'
import RightsList from '@/views/Rights'
import RolesList from '@/views/Roles'
import GoodsList from '@/views/Goods'
import GoodsAdd from '@/views/Goods/add'
import GoodsCategory from '@/views/GoodsCategory'
import OrderList from '@/views/Orders'
import EchartsDemo from '@/views/EchartsDemo'

Vue.use(Router)

const router = new Router({
  routes: [
    { path: '/login', component: Login }, // 展示到App.vue的router-view中
    {
      path: '/', // 展示到App.vue的router-view中
      component: Layout,
      children: [ // 嵌套路由
        // 展示 /home 的时候，先展示父路由视图，然后子路由视图展示到父路由的router-view出口中
        { path: '', component: Home },
        { path: '/users', component: UserList }, // 请求父路由路径的时候，默认渲染path为空的这个子路由
        { path: '/rights', component: RightsList },
        { path: '/roles', component: RolesList },
        { path: '/goods', component: GoodsList },
        { path: '/toadd', component: GoodsAdd },
        { path: '/categories', component: GoodsCategory },
        { path: '/orders', component: OrderList },
        { path: '/echarts', component: EchartsDemo }
      ]
    }
  ]
})
/**
 * to 去哪儿
 * from 来自哪里
 * next 放行规则
 */
router.beforeEach((to, from, next) => {
  // 如果路由路径是 /login 则直接允许通过
  if (to.path === '/login') {
    return next()
  }
  // // 校验登录状态
  // const token = window.localStorage.getItem('token')
  const token = getToken()
  // // 如果没有登录，跳转到登录页
  if (!token) {
    return next('/login')
  }
  // 如果有token,则校验token的有效性
  // token是服务器签发生成的，客户端不能校验
  // 如果登录了，允许通过
  next()
})
export default router
